import urllib
import re
from BeautifulSoup import BeautifulSoup


class MetroNorthDao:
    
    REQUEST_URL = "http://as0.mta.info/mnr/schedules/sched_form.cfm"
    SUBMIT_URL = "http://as0.mta.info/mnr/schedules/sched_results.cfm"
    PATTERN_OBJECT = re.compile('(\d+:\d+ (AM|PM))')
    
    
    def __init__(self):
        remoteSite = urllib.urlopen(MetroNorthDao.REQUEST_URL)
        self.webpageSoup = BeautifulSoup(remoteSite)
        self.__loadStationOptions()
        self.__defaultSubmissionParams()
    
    def getSchedulesByName(self, origStation, destStation, travelDate, time, amOrPm):
        if not self.reverseStations.has_key(origStation):
            raise "Original station %s is not valid" % origStation
        
        if not self.reverseStations.has_key(destStation):
            raise "Destination station %s is not valid" % destStation
        
        origKey = self.reverseStations[origStation]
        destKey = self.reverseStations[destStation]
        
        return self.getSchedulesByKey(origKey, destKey, travelDate, time, amOrPm)
    
    def getSchedulesByKey(self, origStationKey, destStationKey, travelDate, time, amOrPm):
        if not self.stations.has_key(origStationKey):
            raise "Original station %s is not valid" % origStationKey
        
        if not self.stations.has_key(destStationKey):
            raise "Destination station %s is not valid" % destStationKey
        
        self.staticParams["SelAMPM1"] = amOrPm
        self.staticParams["Time_id"] = time
        self.staticParams["orig_id"] = origStationKey
        self.staticParams["dest_id"] = destStationKey
        self.staticParams["traveldate"] = travelDate
        
        return self.__getSchedules()
        
    
    def getStations(self):
        return self.stations
    
    def __getSchedules(self):   
        urlParams = urllib.urlencode(self.staticParams);
        responseHtml = urllib.urlopen(MetroNorthDao.SUBMIT_URL, urlParams).read()
        responseSoup = BeautifulSoup(responseHtml)
        
        #print "%s" % responseSoup
        
        spans = responseSoup("td")
        times = []
        
        for span in spans :
            spanText = str(span.string)
            matchGroups = MetroNorthDao.PATTERN_OBJECT.match(spanText)
            if matchGroups :
                times.append(matchGroups.group(1))
        
                
        trains = self.__createTrainPairs(times)
        return trains
    
    def __createTrainPairs(self,times):
        result = []
        i = 0
        currentTrain = []
        for time in times:
            if i == 0:
                #first time
                currentTrain = []
                currentTrain.append(time)
                result.append(currentTrain)
                i = 1;
            else :
                # Second time
                currentTrain.append(time)
                i = 0
        return result    
            
    
    def __loadStationOptions(self):
        stationOptions = self.webpageSoup("select", id="orig_station")[0].findAll("option")
        self.stations = {}
        self.reverseStations = {}
        
        for stationOption in stationOptions:
            key = stationOption["value"]
            value = stationOption.string
            self.stations[key] = value
            self.reverseStations[value]=key
    
    def __defaultSubmissionParams(self):
        # Things we dont need to change
        self.staticParams = {}      
        self.staticParams["cmdschedule.x"] = "44"
        self.staticParams["cmdschedule.y"] = "19"       
        self.staticParams["Filter_id"] = "1"          

        # Things we need to set
        self.staticParams["SelAMPM1"] = "PM"
        self.staticParams["Time_id"] = "12:00"
        self.staticParams["orig_id"] = "1"
        self.staticParams["dest_id"] = "128"
        self.staticParams["traveldate"] = "05-23-2011"

if __name__ == '__main__':
    dao = MetroNorthDao()    
    #trains = dao.getSchedulesByKey('DA  3', 'GCT 0', "04/26/2009", "12:00", "PM")
    trains = dao.getSchedulesByName('DARIEN', 'STAMFORD', "05/23/2011", "01:30", "PM")   
    
    print "TRAINS"
    
    for train in trains:
        print "%s %s" % (train[0],train[1])
          
        
        